package com.xiongyingqi.openfire.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * 顺序发生器
 * 
 * @author XiongYingqi
 */
public class SequenceGenerator {
	private static Properties properties = new Properties();
	private static File configFile = new File("sequence.properties");
	private static FileInputStream configInputStream;
	private static FileOutputStream configOutputStream;
	private static Integer nextInt;
	static {
		if (!configFile.exists()) {
			try {
				configFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			System.out.println(configFile.getCanonicalPath());
		} catch (IOException e2) {
			e2.printStackTrace();
		}
		try {
			configInputStream = new FileInputStream(configFile);
			properties.load(configInputStream);
			if (!properties.containsKey("nextInt")) {
				properties.put("nextInt", 0);
			}
			nextInt = Integer.parseInt(properties.get("nextInt") + "");
			configOutputStream = new FileOutputStream(configFile);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取下一个数值
	 * @return
	 */
	public static int nextInt() {
		synchronized (nextInt) {
			nextInt++;
			properties.setProperty("nextInt", nextInt + "");
			saveProperties();
		}
		return nextInt;
	}

	public static void saveProperties() {
		try {
			properties.store(configOutputStream, "下一个序列号");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				configOutputStream.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			System.out.println(nextInt());
		}
	}
}
